<template>
  <el-row type="flex" justify="center" align="middle">
    <el-col>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="80px"
        status-icon
      >
        <el-form-item label="标题" prop="title" :rules="rules.title">
          <el-input
            v-model="ruleForm.title"
            :placeholder="placeInfo"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="封面图片">
          <picture-wall ref="pictureWall"></picture-wall>
        </el-form-item>
        <el-form-item label="文章">
          <my-ck-editor ref="myCkEditor"></my-ck-editor>
          <!-- <my-vue2-editor ref="myVue2Editor"></my-vue2-editor> -->
        </el-form-item>
        <el-form-item>
          <el-col :span="24">
            <el-button type="primary" @click="onSubmit('ruleForm')"
              >提交</el-button
            >
            <el-button @click="onBack">返回</el-button>
          </el-col>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script lang="ts">
import { Vue, Component, Prop, Ref } from "vue-property-decorator";
import { checkAccount } from "@/apis/Account";
import { regist } from "@/utils/account";
import { getReqDataNew } from "@/utils/http";
import {
  successResponseType,
  failRejectType,
  productCollectionType,
  failDataType,
  successDataType
} from "CustomTypes";
import { isUndefined, isEqual, isNull } from "lodash";
import router from "@/router";
import PictureWall from "@/components/PictureWall.vue";
import ClassicEditor from "@ckeditor/ckeditor5-build-classic";
import CKEditor from "@ckeditor/ckeditor5-vue";
import MyCkEditor from "@/components/MyCkEditorTest.vue";
import {
  reqProductInfo,
  reqProductUpdate,
  reqProductAdd
} from "@/apis/Product";
import { MessageBox } from "element-ui";
import {
  translateTextWithHtml,
  getCKEditor5CloudTempImgUrls,
  getCloudTempImgUrls
} from "@/utils";
import { getImgsTempUrl } from "@/utils/cloud";

@Component({
  name: "ProductAddUpdate",
  components: { PictureWall, MyCkEditor }
})
export default class ProductAddUpdate extends Vue {
  @Prop()
  private data!: string;
  get dataParams(): any {
    return isEqual(this.data, "")
      ? {}
      : JSON.parse(window.decodeURIComponent(this.data));
  }
  private min = 3;
  private max = 50;
  @Ref("pictureWall")
  private readonly pictureWall!: PictureWall;
  @Ref("myCkEditor")
  private readonly myCkEditor!: MyCkEditor;

  /**
   * 根据传入的id，再次请求得到的商品信息。
   */
  info: productCollectionType = {
    _id: "",
    __v: -1,
    article: "",
    articleText: "",
    cascaderText: "",
    cascaderId: "",
    imgs: [],
    pCategoryId: "",
    status: 1,
    title: ""
  };
  placeInfo = `请输入${this.min} 到 ${this.max}位数的标题`;

  ruleForm = {
    title: ""
  };

  rules = {
    title: [
      { required: true, message: "请输入标题", trigger: "blur" },
      {
        min: this.min,
        max: this.max,
        message: `标题的长度需要在 ${this.min} 到 ${this.max} 个字符之间`,
        trigger: "blur"
      }
    ]
  };

  formData: any;

  onSubmit(formName: string) {
    let flag = false;

    // 验证
    this.formData = this.$refs[formName];
    this.formData.validate(async (valid: any) => {
      if (!valid) return;
      if (!isEqual(this.ruleForm.title, this.info.title)) {
        this.info.title = this.ruleForm.title;
        flag = true;
      }

      if (!isEqual(this.pictureWall.fileListSubmit, this.info.imgs)) {
        this.info.imgs = this.pictureWall.fileListSubmit;
        flag = true;
      }

      if (!isEqual(this.myCkEditor.editorData, this.info.article)) {
        // 获取ckeditor5的文章html数据中的所有临时url，tempUrls是数组
        const tempUrls = getCKEditor5CloudTempImgUrls(
          this.myCkEditor.editorData
        );
        if (!isNull(tempUrls)) {
          // e的数据类型举例：
          // srcset="https://6361-cake-shop-001-gppbo-1258172236.tcb.qcloud.la/uploads/1601095289823_timg.jpg 0w" sizes="100vw"
          const tempUrlsNew = tempUrls.map(e => {
            // 找到临时地址
            const tempUrl = getCloudTempImgUrls(e);
            if (isNull(tempUrl)) return;
            // 找到临时地址的第一个index
            const firstIndex = e.indexOf(tempUrl[0]);
            // 找到临时地址的最后一个index
            const lastIndex = firstIndex + tempUrl[0].length;
            // 获取临时地址的最后一个index到结尾的字符串
            // 举例： 0w" sizes="100vw
            const tempLastStr = e.slice(lastIndex);
            // 替换e中的，不需要的字符串为 ''
            const tempStr1 = e.replace(tempLastStr, '"');
            // 替换标签
            const tempStr2 = tempStr1.replace("srcset", "src");
            return tempStr2;
          });

          if (isUndefined(tempUrlsNew)) return;

          /**
           * 以上得到的 tempUrlsNew 是可以显示的img的url
           * 现在需要替换CKEditor5中的所有的img的url
           */
          let endData = this.myCkEditor.editorData;
          tempUrlsNew.forEach((e, index) => {
            if (isUndefined(e)) return;
            endData = endData.replace(tempUrls[index], e);
          });
          this.info.article = endData;
        }
        flag = true;
      }

      if (flag) {
        let result;
        if (isEqual(this.info._id, "") || !isUndefined(this.info.__v)) {
          delete this.info._id;
          delete this.info.__v;
          result = await reqProductAdd(this.info);
        } else result = await reqProductUpdate(this.info);
        const { flag, data } = getReqDataNew(result);

        if (flag) {
          //得到数据 (data as successDataType).data;
          this.onBack();
          return;
        }

        MessageBox.alert((data as failDataType).msg, {
          confirmButtonText: "确定",
          type: "error"
        });
      }
    });
  }

  onBack() {
    router.back();
  }

  async init() {
    if (isUndefined(this.dataParams.data) || isEqual("", this.dataParams.data))
      return;
    const result = await reqProductInfo(this.dataParams.data);
    const { flag, data } = getReqDataNew(result);
    let resultData;

    if (flag) {
      this.info = (data as successDataType).data;
      // 填充标题
      this.ruleForm.title = this.info.title;
      // 解析封面的临时下载地址
      if (!isEqual([], this.info.imgs)) {
        const { fileList } = await getImgsTempUrl(this.info.imgs);
        this.pictureWall.fileList = fileList.map((file: any) => ({
          name: file.name,
          url: file.url
        }));
      }
      // 解析图片的临时下载地址
      if (!isUndefined(this.info.article)) {
        const data = await translateTextWithHtml(this.info.article);
        this.myCkEditor.editorData = data;
        this.info.article = data;
      }
      return;
    }

    MessageBox.alert((data as failDataType).msg, {
      confirmButtonText: "确定",
      type: "error"
    });
  }

  mounted() {
    this.init();
  }
}
</script>

<style>
.container {
  height: 100% !important;
}
.custom-box {
  width: fit-content;
  margin-left: -80px;
}
.custom-btn {
  display: flex;
  align-content: center;
  justify-content: center;
}
</style>
